﻿using SD.Infrastructure.Repository.EntityFrameworkCore;
using SD.Infrastructure.RepositoryBase;
using SlamDunk.MES.Domain.Entities.ResourceContext;
using SlamDunk.MES.Domain.Entities.StockContext;
using SlamDunk.MES.Domain.IRepositories.Interfaces.StockContext;
using SlamDunk.MES.ReportView.Models;
using SlamDunk.ValueObjects.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace SlamDunk.MES.Repository.Implements.StockContext
{
    /// <summary>
    /// 出/入库记录仓储实现
    /// </summary>
    public class BoundRecordRepository : EFAggRootRepositoryProvider<BoundRecord>, IBoundRecordRepository
    {
        #region # 分页获取出/入库记录列表 —— ICollection<BoundRecord> FindByPage(Guid? materialId...
        /// <summary>
        /// 分页获取出/入库记录列表
        /// </summary>
        /// <param name="materialId">物料定义Id</param>
        /// <param name="materialLotId">物料批次Id</param>
        /// <param name="directionType">出/入库方向类型</param>
        /// <param name="storageLocationType">储存位置类型</param>
        /// <param name="storageLocationId">储存位置Id</param>
        /// <param name="stockOrderClassId">库存单据类Id</param>
        /// <param name="stockOrderId">库存单据Id</param>
        /// <param name="facilityIds">工厂模型Id集</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="rowCount">总记录数</param>
        /// <param name="pageCount">总页数</param>
        /// <returns>出/入库记录列表</returns>
        public ICollection<BoundRecord> FindByPage(Guid? materialId, Guid? materialLotId, StockDirectionType? directionType, StorageLocationType? storageLocationType, string storageLocationId, Guid? stockOrderClassId, Guid? stockOrderId, IList<Guid> facilityIds, int pageIndex, int pageSize, out int rowCount, out int pageCount)
        {
            Expression<Func<BoundRecord, bool>> condition =
                x =>
                    (materialId == null || x.MaterialId == materialId) &&
                    (materialLotId == null || x.MaterialLotId == materialLotId) &&
                    (directionType == null || x.DirectionType == directionType) &&
                    (storageLocationType == null || x.StorageLocationType == storageLocationType) &&
                    (string.IsNullOrEmpty(storageLocationId) || x.StorageLocationId == storageLocationId) &&
                    (stockOrderClassId == null || x.StockOrderClassId == stockOrderClassId) &&
                    (stockOrderId == null || x.StockOrderId == stockOrderId);

            IQueryable<BoundRecord> boundRecords = base.Find(condition);
            if (facilityIds != null && facilityIds.Any())
            {
                boundRecords = boundRecords.Where(x => x.FacilityId.HasValue && facilityIds.Contains(x.FacilityId.Value));
            }

            IOrderedQueryable<BoundRecord> orderedResult = boundRecords.OrderByDescending(x => x.AddedTime);
            IQueryable<BoundRecord> pagedResult = orderedResult.ToPage(pageIndex, pageSize, out rowCount, out pageCount);

            return pagedResult.ToList();
        }
        #endregion

        #region # 获取作业计划物料概要列表 —— ICollection<MaterialSummaryInfo> GetMaterialSummariesByExecutionPlan(...
        /// <summary>
        /// 获取作业计划物料概要列表
        /// </summary>
        /// <param name="executionPlanId">作业计划Id</param>
        /// <param name="directionType">出/入库类型</param>
        /// <returns>物料概要列表</returns>
        public ICollection<MaterialSummaryInfo> GetMaterialSummariesByExecutionPlan(Guid executionPlanId, StockDirectionType directionType)
        {
            string executionPlanIdText = executionPlanId.ToString();
            IQueryable<MaterialSummaryInfo> materialSummaries;

            if (directionType == StockDirectionType.Input)
            {
                materialSummaries = this.GetMaterialSummariesBySourceOrder(SourceOrderType.ExecutionPlan, executionPlanIdText, StockDirectionType.Input);

                //获取作业计划相关出库单列表
                IQueryable<Guid> stockOutOrderIds =
                    from stockOutOrder in base._dbContext.Set<StockOutOrder>()
                    where stockOutOrder.SourceOrderType == SourceOrderType.ExecutionPlan &&
                          stockOutOrder.SourceOrderId == executionPlanIdText
                    select stockOutOrder.Id;

                //获取出库单相关的入库记录
                foreach (Guid stockOutOrderId in stockOutOrderIds)
                {
                    string stockOutOrderIdText = stockOutOrderId.ToString();
                    IQueryable<MaterialSummaryInfo> partMaterialSummaries = this.GetMaterialSummariesBySourceOrder(SourceOrderType.OutboundOrder, stockOutOrderIdText, StockDirectionType.Input);
                    materialSummaries = materialSummaries.Union(partMaterialSummaries);
                }
            }
            else if (directionType == StockDirectionType.Output)
            {
                materialSummaries = this.GetMaterialSummariesBySourceOrder(SourceOrderType.ExecutionPlan, executionPlanIdText, StockDirectionType.Output);
            }
            else
            {
                throw new NotSupportedException();
            }

            return materialSummaries.ToList();
        }
        #endregion


        //Private

        #region # 根据源单据获取物料概要列表 —— ICollection<MaterialSummaryInfo> GetMaterialSummariesByExecutionPlan(...
        /// <summary>
        /// 根据源单据获取物料概要列表
        /// </summary>
        /// <param name="sourceOrderType">源单据类型</param>
        /// <param name="sourceOrderId">源单据Id</param>
        /// <param name="directionType">出/入库类型</param>
        /// <returns>物料概要列表</returns>
        private IQueryable<MaterialSummaryInfo> GetMaterialSummariesBySourceOrder(SourceOrderType sourceOrderType, string sourceOrderId, StockDirectionType directionType)
        {
            IQueryable<Guid> stockOrderIds = base._dbContext.Set<StockOrder>()
                 .Where(x => x.SourceOrderType == sourceOrderType &&
                             x.SourceOrderId == sourceOrderId &&
                             x.DirectionType == directionType)
                 .Select(x => x.Id);

            IQueryable<BoundRecord> boundRecords = base.Find(x => stockOrderIds.Contains(x.StockOrderId));
            var boundRecordGroups = boundRecords.GroupBy(x => new
            {
                x.MaterialId,
                x.MaterialLotId
            }).Select(x => new
            {
                x.Key,
                Quantity = x.Any() ? x.Sum(y => y.Quantity) : (decimal?)null
            });

            IQueryable<Material> materials = this._dbContext.Set<Material>();
            IQueryable<MaterialLot> materialLots = this._dbContext.Set<MaterialLot>();
            IQueryable<MaterialSummaryInfo> materialSummaries =
                from boundRecordGroup in boundRecordGroups
                let material = materials.FirstOrDefault(x => x.Id == boundRecordGroup.Key.MaterialId)
                let materialLot = boundRecordGroup.Key.MaterialLotId.HasValue
                    ? materialLots.FirstOrDefault(x => x.Id == boundRecordGroup.Key.MaterialLotId.Value)
                    : null
                let quantity = boundRecordGroup.Quantity
                select new MaterialSummaryInfo
                {
                    MaterialId = material.Id,
                    MaterialNo = material.Number,
                    MaterialName = material.Name,
                    MaterialLotId = materialLot == null ? (Guid?)null : materialLot.Id,
                    SupplierId = materialLot == null ? (Guid?)null : materialLot.SupplierId,
                    SupplierNo = materialLot == null ? null : materialLot.SupplierNo,
                    SupplierName = materialLot == null ? null : materialLot.SupplierName,
                    ProductionBatchNo = materialLot == null ? null : materialLot.ProductionBatchNo,
                    ProducedDate = materialLot == null ? (DateTime?)null : materialLot.ProducedDate,
                    GuaranteePeriodTicks = materialLot == null ? (long?)null : materialLot.GuaranteePeriodTicks,
                    ExpiredDate = materialLot == null ? (DateTime?)null : materialLot.ExpiredDate,
                    ReceptionDate = materialLot == null ? (DateTime?)null : materialLot.ReceptionDate,
                    Specification = materialLot == null ? null : materialLot.Specification,
                    MaterialSourceType = materialLot == null ? (MaterialSourceType?)null : materialLot.MaterialSourceType,
                    Quantity = quantity ?? 0,
                    QuantityUnitNo = material.StandardUnitNo
                };

            return materialSummaries;
        }
        #endregion
    }
}
